package main

import (
	"encoding/json"
	"fmt"
	"log"
	"strconv"
)

/*
* Author: JacksonCoder
* CreateTime: 2025-10-31
 */

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	var a int = 100
	var b int64 = int64(a)
	var c float64 = float64(a)
	var d int = int(c) // 可能丢掉小数部分

	fmt.Printf("a = %d \n", a)
	fmt.Printf("b = %d \n", b)
	fmt.Printf("c = %f \n", c)
	fmt.Printf("d = %d \n", d)

	// String -> int
	str := "123"
	num, err := strconv.Atoi(str) // 简写
	if err != nil {
		fmt.Println("转化失败")
	}
	fmt.Printf("num = %d \n", num)

	// 更加精确控制
	num64, err := strconv.ParseInt("123", 10, 64) // base=10 bitSize=64
	num = int(num64)
	fmt.Printf("num = %d \n", num)

	// String -> float
	f, err := strconv.ParseFloat("3.14", 64)
	if err != nil {
		fmt.Println("转化失败")
	}
	fmt.Printf("f = %f \n", f)

	// 数值 -> 字符串
	num = 123
	str = strconv.Itoa(num)
	fmt.Printf("str = %s \n", str)
	// or
	str = strconv.FormatInt(123, 10)
	str = strconv.FormatFloat(3.14, 'f', 2, 64) // 'f' 格式，保留2位小数

	// 字符串 切片
	str = "hello"
	bytes := []byte(str)
	fmt.Println("bytes", bytes)

	// 反过来
	data := []byte{104, 101, 108, 108, 111}
	s := string(data)
	fmt.Printf("s = %s \n", s)

	// bool -> string
	flag := true
	strs := strconv.FormatBool(flag) // "true"
	fmt.Printf("strs = %s \n", strs)
	// string -> bool
	B1, err := strconv.ParseBool("true") // true
	if err != nil {
		fmt.Printf("转化失败")
	}
	fmt.Printf("B1 = %v \n", B1)

	// 结构体转化
	user := User{Name: "alen", Age: 198}

	// struct -> json str
	jsonBytes, _ := json.Marshal(user)
	jsonStr := string(jsonBytes)
	fmt.Println("jsonStr = ", jsonStr)
	fmt.Printf("jsonStr type  =  %T \n", jsonStr)

	// json str -> struct
	var u User
	err = json.Unmarshal([]byte(jsonStr), &u)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("u = %v \n", u)
	fmt.Printf("u type  = %T \n", u)

	// 断言
	var x interface{} = "hello"
	//  断言为 string
	str, ok := x.(string)
	if ok {
		fmt.Println("string is ", str)
	} else {
		fmt.Println("不是 string")
	}

	// 如果能够直接确定类型是 string
	//str2 := x.(string)   // 可以直接

	// switch 判断多种类型
	printType(123)
	printType("123")
	printType(1234.111)
	printType(false)
	printType(true)

	//  []int → []interface{}  Go 不允许直接转换，需要手动遍历
	ints := []int{1,2,3,4,5}
	var anys []interface{}

	for _, v := range ints{
		anys = append(anys,v)
	}


}

func printType(v interface{}) {
	switch val := v.(type) {
	case string:
		fmt.Println("字符串: ", val)
	case int:
		fmt.Println("整数: ", val)
	case bool:
		fmt.Println("布尔: ", val)
	case float32:
		fmt.Println("浮点数: ", val)
	default:
		fmt.Println("未知类型")
	}
}
